package com.nbx.app.zeuscmdport;


import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.opengl.GLU;
import android.view.MotionEvent;

/**
 * http://www.zeuscmd.com/tutorials/opengles/12-Perspective.php
 * 
 *
 */
public class Render12 extends RenderBase {

	private boolean perspective = true;
	private boolean perspectiveUpdated = false;
	
	private int w = 0;
	private int h = 0;

	public Render12(Context context) {
		super(context);
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc(GL10.GL_LEQUAL);

		gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
		gl.glClearDepthf(1.0f);
	}


	public void onSurfaceChanged(GL10 gl, int width, int height) {
		w = width;
		h = height;

		if (height == 0) {
			height = 1;
		}

		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();

		gl.glViewport(0, 0, width, height);

		if (perspective) {
			GLU.gluPerspective(gl, 45.0f, 1.0f * width / height, 1.0f, 100.0f);
		} else {
			gl.glOrthof(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 20.0f);
		}

		perspectiveUpdated = false;

		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
	}

	public void onDrawFrame(GL10 gl) {
		if(perspectiveUpdated){			
			onSurfaceChanged(gl, w, h);
		}
		
		gl.glClear (GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		gl.glLoadIdentity();

		GLU.gluLookAt(gl,
			0.0f, 0.0f, 2.0f,
			0.0f, 0.0f, 0.0f,
			0.0f, 1.0f, 0.0f);

		gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
		gl.glTranslatef(0.25f, 0.0f, 0.0f);
		glutSolidCube(gl, 0.5f);
		//glutSolidCube(0.5f);

		gl.glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
		gl.glTranslatef(-0.25f, 0.0f, -1.0f);
		glutSolidCube(gl, 0.5f);

		gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
		gl.glTranslatef(-0.25f, 0.0f, -1.0f);
		glutSolidCube(gl, 0.5f);
	}
	
	@Override
	public boolean handleTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			perspectiveUpdated = true;
			perspective = !perspective;
			return true;
		}
		return false;
	}
}